﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Windows.Controls;
using Newtonsoft.Json;
using Snap.Extensions;

namespace Snap.Api.Imgur
{
    public class ImgurApi : ApiBase
    {
        private static readonly string API_KEY_ANONYMOUS = "e3e438cf4a9b61855b9aa579a9d554b7";

        /// <summary>
        /// Uploads the processed snapshot to the remote image host.
        /// </summary>
        public override ApiResponseBase UploadSnapshot(byte[] snapshot)
        {
            string dataString = Convert.ToBase64String(snapshot);
            dataString = dataString.EscapeDataString();

            var webRequest = (HttpWebRequest)WebRequest.Create("http://api.imgur.com/2/upload.json");
            webRequest.Method = "POST";
            webRequest.ContentType = "application/x-www-form-urlencoded";
            webRequest.ServicePoint.Expect100Continue = false;

            var streamWriter = new StreamWriter(webRequest.GetRequestStream());
            streamWriter.Write(String.Format("image={0}&key={1}", dataString, API_KEY_ANONYMOUS));
            streamWriter.Close();

            using (var streamReader = new StreamReader(webRequest.GetResponse().GetResponseStream()))
            {
                return JsonConvert.DeserializeObject<ImgurApiResponse>(streamReader.ReadToEnd());
            }
        }
    }
}
